package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cedarsoftware.util.io.JsonWriter;

import business.Pari;
import business.Utilisateur;
import business.utilities.Pari_Package;


public class S_BetAction extends HttpServlet {
	private static final long serialVersionUID = 1L;


	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("json");
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		
		String action = request.getParameter("action");
		Utilisateur utilisateur = (Utilisateur) request.getSession().getAttribute("utilisateur");
		
		// Renvoie les paris en cours.
		if(action == null || action.equals("")) {
			List<Pari> paris = utilisateur.getParis();
			if(paris != null && !paris.isEmpty()) {
				List<Pari_Package> json = new ArrayList<Pari_Package>();
				for(Pari p : paris) {
					Pari_Package pp = new Pari_Package();
					pp.update(p);
					json.add(pp);
				}
				out.print(JsonWriter.objectToJson(json));
			}
			else
				out.print("{}");
		}
		else {
			int id_passageTrainTheorique = Integer.valueOf(request.getParameter("id_passageTrainTheorique"));
			int mise = Integer.valueOf(request.getParameter("mise"));
			int retard = Integer.valueOf(request.getParameter("retard"));
			
			// Nouveau pari.
			if(action.equals("ajouter")) {
				if(utilisateur.ajouterPari(id_passageTrainTheorique, mise, retard))
					out.print("{}");
				else
					response.setStatus(599);
			}
		}
		
		out.close();
	}
}